﻿using System;
using System.IO;

namespace MudEngine.Utils
{
	public class Files
	{
		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static bool Exists(string path)
		{
			if (!path.StartsWith("/"))
				path = Path.DirectorySeparatorChar + path;

			FileInfo fi = new FileInfo(MudContext.LIB_DIR + path);
			return fi.Exists;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		/// <param name="recursive"></param>
		/// <returns></returns>
		public static string[] GetFrom(string path, bool recursive)
		{
			DirectoryInfo di = new DirectoryInfo(MudContext.LIB_DIR);
			if (path.StartsWith("/"))
				path = path.Substring(1);

			FileInfo[] fi = di.GetFiles(path, recursive?SearchOption.AllDirectories:SearchOption.TopDirectoryOnly);
			string[] result = new string[fi.Length];
			for (int i = 0; i < fi.Length; i++)
				result[i] = fi[i].Name;

			return result;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static string Read(string path)
		{
			try
			{
				if (!path.StartsWith("/"))
					path = Path.DirectorySeparatorChar + path;

				FileInfo fi = new FileInfo(MudContext.LIB_DIR + path);
				if (!fi.Exists)
					return string.Empty;

				using (StreamReader reader = fi.OpenText())
				{
					return reader.ReadToEnd();
				}
			}
			catch (Exception e)
			{
                Log.Debug(typeof(Files), "File could not be read.", e);
				return string.Empty;
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		/// <param name="data"></param>
		public static bool Append(string path, string data)
		{
			return Write(path, data, true);
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		/// <param name="data"></param>
		public static bool Write(string path, string data)
		{
			return Write(path, data, false);
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		/// <param name="data"></param>
		/// <param name="append"></param>
		public static bool Write(string path, string data, bool append)
		{
			try
			{
				if (!path.StartsWith("/"))
					path = Path.DirectorySeparatorChar + path;

				using (StreamWriter writer = new StreamWriter(MudContext.LIB_DIR + path, append))
				{
					writer.Write(data);

					return true;
				}
			}
			catch (Exception e)
			{
                Log.Debug(typeof(Files), "File could not be written.", e);
                return false;
			}
		}
	}
}
